package com.example.newsapplication.api;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.newsapplication.activity.LoginActivity;
import com.example.newsapplication.util.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {
    private static OkHttpClient client;
    private static String requestUrl;
    private static HashMap<String, Object> mParams;

    public static Api api = new Api();

    public Api() {
    }

    public static Api config(String url, HashMap<String, Object> params) {
        client = new OkHttpClient.Builder().build();
        requestUrl = ApiConfig.BASE_URl + url;
        mParams = params;
        return api;
    }

    public void get(Context context, final ApiCallback callback) {
        SharedPreferences sp = context.getSharedPreferences("sp_ttit", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        String url = getAppendUrl(requestUrl, mParams);
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                handleResponse(context,response,callback);
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handleFailure(e,callback);
            }
        });

    }


    public void post(Context context, final ApiCallback callback) {
        SharedPreferences sp = context.getSharedPreferences("sp_ttit", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");
        JSONObject jsonObject = new JSONObject(mParams);
        String jsonStr = jsonObject.toString();
        // 将字符串转换为字节数组
        byte[] jsonBytes = jsonStr.getBytes(StandardCharsets.UTF_8);
        // 创建 MediaType
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        // 使用 RequestBody.create 方法
        RequestBody requestBodyJson = RequestBody.create(jsonBytes,mediaType);

        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(requestUrl)
                .post(requestBodyJson)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                handleFailure(e,callback);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                handleResponse(context,response,callback);
            }
        });
    }

    private String getAppendUrl(String url, HashMap<String, Object> map) {
      if(map!=null && !map.isEmpty()){
          StringBuilder sb = new StringBuilder();
          Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
          while (iterator.hasNext()){
              Map.Entry<String, Object> entry = iterator.next();
              if (StringUtils.isEmpty(sb.toString())){
                  sb.append("?");
              }else{
                  sb.append("&");
              }
              sb.append(entry.getKey()).append("=").append(entry.getValue());
          }
          url += sb.toString();
      }
      return url;
    }
    private void handleResponse(Context context,@NonNull Response response,final ApiCallback callback)  throws IOException {
        switch (response.code()){
            case 200:
                final String result = response.body().string();
                Log.d("Api", "requestUrl:"+requestUrl);
                Log.d("Api", "result:"+result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int code = jsonObject.getInt("code");
                    switch (code){
                        case 0:
                            callback.onSuccess(result);
                            return;
                        case 401:
                            Intent in = new Intent(context, LoginActivity.class);
                            if (in.resolveActivity(context.getPackageManager()) != null) {
                                context.startActivity(in);
                            }
                            callback.onFailure(new Exception("请先登录"));
                            return;
                        case 403:
                            callback.onFailure(new Exception("没有权限"));
                            return;
                        default:
                            callback.onFailure(new Exception(jsonObject.getString("msg")));
                    }
                } catch (JSONException e) {
                    Log.d("Api", "JSONException:"+e.getMessage());
                    e.printStackTrace();
                }
                break;
            case 400:
                callback.onFailure(new Exception("请求参数错误"));
                return;
            case 401:
                callback.onFailure(new Exception("请先登录"));
                return;
            case 403:
                callback.onFailure(new Exception("没有权限"));
                return;
            case 404:
                callback.onFailure(new Exception("请求路径错误"));
                return;
            case 500:
                callback.onFailure(new Exception("服务器错误"));
        }

    }
    private void handleFailure(Exception e,final ApiCallback callback){
        Exception err = e.getMessage() == null ? new Exception("No error message") : e;
        Log.e("onFailure", requestUrl +" :" + err.getMessage());
        callback.onFailure(err);
    }
    public static void cancelAllRequests(){
        client.dispatcher().cancelAll();
    }

}

